import React, { useEffect, useState } from 'react'
import { useAppDispatch } from '@/hooks'
import {
    batchDeleteHospSetAsync,
    deleteHospSetAsync,
    getHospSetListAsync,
    lockHospSetAsync,
    upSearchData,
    useSelectorHosp
} from '@/store/slice/hosp'
import { Button, Form, Input, message, Popconfirm, Space, Switch, Table, Tooltip } from 'antd'
import { DeleteOutlined, FormOutlined, SearchOutlined } from '@ant-design/icons'
import { useSelectPageCommon } from '@/store/slice/pageCommon'
import HospSetMadel from '@/pages/hospital/hospitalSet/components/HospSetMadel'

function HospitalSet() {
    // 多选框和批量删除相关
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
    const [loading, setLoading] = useState(false)
    const start = () => {
        setLoading(true)
        setTimeout(() => {
            setSelectedRowKeys([])
            setLoading(false)
        }, 1000)
    }
    // 控制批量删除按钮的显示与隐藏
    const hasSelected = selectedRowKeys.length > 0

    const dispatch = useAppDispatch()
    const { hospSetList, searchData } = useSelectorHosp()
    const { pageInfo } = useSelectPageCommon()
    useEffect(() => {
        dispatch(getHospSetListAsync(1, 5))
        return () => {
            dispatch(upSearchData({})) // 清空搜索条件,解决切换路由时,搜索条件还存在的问题
        }
    }, [])

    // 控制modal的显示与隐藏
    const [isModalVisible, setIsModalVisible] = useState<boolean>(false)
    // 控制modal的标题
    const [modalTitle, setModalTitle] = useState<string>('添加医院设置')
    // 控制modal的数据
    const [modalData, setModalData] = useState<any>(null)

    const [form] = Form.useForm() // 获取form实例
    // console.log(searchData)
    return (
        <div>
            <div style={{ marginBottom: 16 }}>
                <Form
                    form={form}
                    name="basic"
                    initialValues={{ remember: true }}
                    onFinish={async () => {
                        dispatch(upSearchData(form.getFieldsValue())) // 将搜索条件保存到redux中
                        await dispatch(getHospSetListAsync(1, 5))
                    }}
                    autoComplete="off"
                    layout="inline" // 表单布局
                >
                    <Form.Item name="hosname">
                        <Input placeholder={'请输入医院名称'} />
                    </Form.Item>
                    <Form.Item name="hoscode">
                        <Input placeholder={'请输入医院编码'} />
                    </Form.Item>

                    <Form.Item>
                        <Button icon={<SearchOutlined />} type="primary" htmlType="submit">
                            搜索
                        </Button>
                    </Form.Item>
                    <Form.Item>
                        <Button
                            onClick={() => {
                                dispatch(upSearchData({}))
                                dispatch(getHospSetListAsync(1, 5))
                                form.resetFields() // 重置表单
                            }}
                        >
                            重置
                        </Button>
                    </Form.Item>
                </Form>
            </div>

            <Space style={{ marginBottom: 16 }}>
                <Button
                    type="primary"
                    onClick={() => {
                        setModalData({})
                        setModalTitle('添加医院设置')
                        setIsModalVisible(true)
                    }}
                >
                    添加
                </Button>
                <Button
                    type="primary"
                    disabled={selectedRowKeys.length === 0} // 没有选中的时候禁用
                    onClick={() => {
                        start()
                        // 批量删除
                        dispatch(batchDeleteHospSetAsync(selectedRowKeys))
                    }}
                    loading={loading}
                >
                    批量删除{selectedRowKeys.length}条
                </Button>
            </Space>

            <Table
                dataSource={hospSetList.records}
                rowKey={'id'}
                // 多选框
                rowSelection={{
                    selectedRowKeys,
                    onChange: (newSelectedRowKeys: React.Key[]) => {
                        // console.log('selectedRowKeys changed: ', selectedRowKeys)
                        setSelectedRowKeys(newSelectedRowKeys)
                    }
                }}
                bordered={true} // 边框
                scroll={{ x: 1800 }}
                pagination={{
                    ...pageInfo,
                    onChange: (page, pageSize) => {
                        dispatch(getHospSetListAsync(page, pageSize))
                    }
                }} // 是否展示分页
                columns={[
                    {
                        title: '序号',
                        width: 70,
                        align: 'center', // 居中
                        dataIndex: 'id',
                        render: (value, record, index) => {
                            return (pageInfo.current - 1) * pageInfo.pageSize + index + 1
                        }
                    },
                    {
                        title: '医院名称',
                        width: 200,
                        ellipsis: true, // 超出省略
                        align: 'center',
                        dataIndex: 'hosname'
                    },
                    {
                        title: '医院编号',
                        align: 'center',
                        dataIndex: 'hoscode'
                    },
                    {
                        title: '是否锁定',
                        width: 100,
                        align: 'center',
                        // 0 锁定 1 未锁定
                        dataIndex: 'status',
                        render: (status, record) => {
                            return (
                                <Switch
                                    checked={status === 0}
                                    onChange={() => {
                                        dispatch(lockHospSetAsync(record.id, status))
                                    }}
                                />
                            )
                        }
                    },
                    {
                        title: '基础api',
                        align: 'center',
                        dataIndex: 'apiUrl'
                    },
                    {
                        title: '签名秘钥',
                        align: 'center',
                        ellipsis: true, // 超出省略
                        dataIndex: 'signKey'
                    },
                    {
                        title: '联系人姓名',
                        width: 120,
                        align: 'center',
                        dataIndex: 'contactsName'
                    },
                    {
                        title: '联系人手机',
                        align: 'center',
                        dataIndex: 'contactsPhone'
                    },
                    {
                        title: '创建时间',
                        align: 'center',
                        dataIndex: 'createTime'
                    },
                    {
                        title: '修改时间',
                        align: 'center',
                        dataIndex: 'updateTime'
                    },
                    {
                        title: '操作',
                        width: 150,
                        align: 'center',
                        fixed: 'right', // 右浮动
                        // 如果没有dataIndex，那么render的第一个参数就是当前行的数据
                        render: (record) => {
                            return (
                                // 编辑和删除按钮
                                <Space>
                                    <Tooltip title="编辑">
                                        <Button
                                            type="primary"
                                            shape="circle"
                                            icon={<FormOutlined />}
                                            onClick={() => {
                                                // 修改当前项的数据
                                                setModalTitle('编辑医院设置')
                                                setModalData({ ...record })
                                                setIsModalVisible(true)
                                            }}
                                        />
                                    </Tooltip>

                                    <Popconfirm
                                        placement="topRight"
                                        title={'确定删除吗？'}
                                        onConfirm={() => {
                                            dispatch(deleteHospSetAsync(record.id)).then(() => {
                                                message.success('删除成功')
                                            })
                                        }}
                                        okText="是"
                                        cancelText="否"
                                    >
                                        <Tooltip title="删除">
                                            <Button danger type="primary" shape="circle" icon={<DeleteOutlined />} />
                                        </Tooltip>
                                    </Popconfirm>
                                </Space>
                            )
                        }
                    }
                ]}
            ></Table>
            <HospSetMadel
                modalTitle={modalTitle}
                setIsModalVisible={setIsModalVisible}
                isModalVisible={isModalVisible}
                modalData={modalData}
            />
        </div>
    )
}

export default HospitalSet
